<?php
namespace Home\Controller;

use Common\Controller\HomeController;
use Think\Controller;
use Think\Log;

class SendSmsController extends HomeController
{
    /**
     * 发送模板短信
     * @author Mr.Alien
     * @param $to mixed 手机号码集合,用英文逗号分开
     * @param $data mixed 内容数据 格式为数组 例如：array('Marry','Alon')，如不需替换请填 null
     * @param $tempId string 模板Id
     * @return mixed
     */
    function index($p=1)
    {
        set_time_limit(0);
        ignore_user_abort(true);
        $data = I('post.');
        (count($data['ids']) < 1) && $this->error('无发送数据');
        $mess_number = M('MessNumber')->where(array('user_id'=>session('id')))->find();
        if(!$mess_number || count($data['ids']) > ($mess_number['capacity']-$mess_number['used'])){
            $this->error('短信可用量不足');
        }
        $content = D("MessContent")->relation(true)->where(array('id'=>(int)$data['template_id']))->find();
        $take_list = M("Take")->where(array('id'=>array('in',$data['ids'])))->select();
        $phone_list = array();
        foreach($take_list as $key => $value){       
                 $phone_list[] = $value['phone'];
        }

        $this->bunchSendMsg($phone_list, $content);

        M('MessNumber')->where(array('user_id'=>session('id')))->setInc('used',count($data['ids']));
        M('Take')->where(array('id'=>array('in',$data['ids'])))->save(array('mess_status'=>2));

        $insert_list = array();
        foreach($take_list as $key => $value){
            $insert_list[] = array(
                'take_id' => $value['id'],
                'no'      => $value['no'],
                'phone'   => $value['phone'],
                'user_id' => session('id'),
            );
        }
        $this->bunchInsertSql($insert_list);

        $this->success('已加入到发送队列');
    }

    public function bunchSendMsg($phones, $content) {
        $i = 0;
        while(1 && $i < 10) {
            if (empty($phones)) return;
            //每次选取200个
            $tmp = array_splice($phones, 0, 200);
            //发送短信
           $res = D("Send")->sms(implode(',',$tmp), array(
                $content['one_para'],
                $content['two_para'],
                $content['three_para'],
                $content['four_para']
            ),$content['template']['temp_id']);
            //休眠0.1s
            usleep(100000);
            $i++;
        }
    }

    public function bunchInsertSql($insert_list) {
        $i = 0;
        while(1 && $i < 20) {
            if (empty($insert_list)) return;
            //每次选取200个
            $tmp = array_splice($insert_list, 0, 50);
            M('MessRecord')->addAll($tmp);
            $i++;
        }
    }

}